<template>
    测试页面<br />
    <a-input v-model:value="value"></a-input><br />
    <a-button type="primary" @click="addData">测试按钮:添加数据</a-button><br />
    <a-button type="primary" @click="getData">测试按钮:获取id为{{ value }}数据</a-button><br />
    <a-button @click="getAllData">测试按钮:获取数据</a-button><br />
    <a-button @click="updateData">测试按钮:更新id为{{ value }}数据</a-button><br />
    <a-button @click="deleteData">测试按钮:删除id为{{ value }}数据</a-button><br />

    <li v-for="item in tableData" :key="item.id">{{ item.id }} - {{ item.name }} - {{ item.email }}</li>
</template>
<script setup lang="ts">
import IndexedDB from '@/utils/IndexedDB'
import { onMounted, onUnmounted, ref } from 'vue'

const value = ref('')

const db = new IndexedDB('myDatabase')


const tableData = ref<any>([])

const id = ref(0)

onMounted(async () => {
    await db.openDB('users');
})

// const data = {
//     id,
//     name: `${id.value}-测试姓名`,
//     email: `${id.value}-测试邮箱@test.com`
// }
async function addData() {
    // id.value++
    // await db.openDB('testTable')
    // // db.createObjectStore('test')
    // const data = {
    //     id: id.value,
    //     name: `${id.value}-测试姓名`,
    //     email: `${id.value}-测试邮箱@test.com`
    // }

    // const result = await db.addData('testTable', data)

    // console.log('添加数据结果:', result);
    const userId = await db.addData('users', {
        time: new Date().toLocaleString('zh-CN'),
        name: '张三',
        email: 'zhangsan@example.com'
    });
    console.log('新用户 ID:', userId);
}

async function getData() {
    // await db.openDB('testTable')
    // const data = await db.getData('testTable', Number(value.value))
    // tableData.value = data
    // console.log(data)
    // 查询数据
    const user = await db.getData('users', Number(value.value))

    console.log('用户:', user);

}

async function getAllData() {
    // await db.openDB('users')
    const data = await db.getAllData('users',)
    tableData.value = data
    console.log(data)
}

async function updateData() {
    // await db.openDB('testTable')
    const data = await db.updateData('users', Number(value.value), {
        id: Number(value.value),
        name: `${Number(value.value)}-update`,
        email: `${Number(value.value)}-update邮箱`,
        img: 'adadadadadad'
    })
    console.log(data)
}

async function deleteData() {

    await db.openDB('users')
    const data = await db.deleteData('users', Number(value.value))
    console.log(data)
}

onUnmounted(() => {

    db.closeDB()
})
</script>
<style lang="scss" scoped></style>